package com.fast.security.config;

import com.fast.security.handle.Http401AuthenticationEntryPoint;
import com.fast.security.provider.TokenProvider;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;

/**
 * Class WebSecurityConfig
 *
 * @Auther: lhy
 * @Date: 2021/12/6 11:02
 * @Mail: 190643201@qq.com
 */

@Slf4j
@AllArgsConstructor
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    private final TokenProvider tokenProvider;
    private final UserDetailsService userDetailsService;
    private final PermissionEvaluator permissionEvaluatorImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable() // 禁用 Spring Security 自带的跨域处理
                .exceptionHandling()
                .authenticationEntryPoint(
                        new Http401AuthenticationEntryPoint("Basic realm=\"MyApp\"")
                ).and()
                .authorizeRequests()
                .antMatchers("/open/*").permitAll()
                .anyRequest().authenticated()    // 剩下所有的验证都需要验证
                .and().apply(new JWTConfigurer(tokenProvider, userDetailsService));
        http.authorizeRequests().expressionHandler(defaultWebSecurityExpressionHandler());
    }


    @Bean
    public DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler() {
        DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
        defaultWebSecurityExpressionHandler.setPermissionEvaluator(permissionEvaluatorImpl);
        return defaultWebSecurityExpressionHandler;
    }

}
